<template>
  <Breadcrumb class="breadcrumb" separator="/">
    <!-- <transition-group name="breadcrumb"> -->
    <BreadcrumbItem v-for="(item, index) in breadcrumbs" :key="item.path">
      <span
        v-if="!item.isBreadcrumbJump || index === breadcrumbs.length - 1"
        class="no-redirect breadcrumb-color"
        >{{ item.meta.title }}</span
      >
      <a class="breadcrumb-color" v-else @click.prevent="handleLink(item)">{{
        item.meta.title
      }}</a>
    </BreadcrumbItem>
    <!-- </transition-group> -->
  </Breadcrumb>
</template>

<script lang="ts">
import { compile } from "path-to-regexp";
import { Component, Vue, Watch } from "vue-property-decorator";
import { RouteRecord, Route } from "vue-router";

@Component({
  name: "dxBreadcrumb"
})
export default class extends Vue {
  private breadcrumbs: RouteRecord[] = [];

  @Watch("$route")
  private onRouteChange(route: Route) {
    // 重定向页面不更新面包屑导航
    if (route.path.startsWith("/redirect/")) {
      return;
    }
    this.getBreadcrumb();
  }

  created() {
    this.getBreadcrumb();
  }

  private getBreadcrumb() {
    // 获取面包屑导航数据
    const matched = this.$route.matched.filter(
      item => item.meta && item.meta.title
    );
    // const first = matched[0];
    // if (!this.isDashboard(first)) {
    //   matched = [
    //     { path: '/dashboard', meta: { title: 'Dashboard' } } as RouteRecord
    //   ].concat(matched)
    // }
    this.breadcrumbs = matched.filter(item => {
      return item.meta && item.meta.title && item.meta.breadcrumb !== false;
    });
  }

  // private isDashboard(route: RouteRecord) {
  //   const name = route && route.meta && route.meta.title;
  //   console.log(name);
  //   return name === "Dashboard";
  // }

  private pathCompile(path: string) {
    const { params } = this.$route;
    const toPath = compile(path);
    return toPath(params);
  }

  private handleLink(item: any) {
    const { redirect, path } = item;
    if (redirect) {
      this.$router.push(redirect);
      return;
    }
    console.log("跳转的地址", this.pathCompile(path));
    this.$router.push(this.pathCompile(path));
  }
}
</script>

<style lang="less" scoped>
@breadcrumb-color: #fff;
.breadcrumb {
  display: flex;
  height: 100%;
  justify-content: flex-start;
  align-items: center;
  .breadcrumb-color {
    color: @breadcrumb-color;
  }
  ::v-deep .@{css-prefix}breadcrumb-separator {
    color: @breadcrumb-color;
  }
}
</style>
